package com.logic.landseaserver.ws;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.exception.BusinessException;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.common.util.PagingTool;
import com.logic.common.util.QueryCriteria;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.domain.Procedure;
import com.logic.landseaserver.domain.RemouldProject;
import com.logic.landseaserver.domain.ReportStrip;
import com.logic.landseaserver.service.IProperty;
import com.logic.landseaserver.service.IRemouldProjectService;
import com.logic.landseaserver.service.IReportStripService;
import com.logic.landseaserver.service.utils.ResetQueryUtil;
import com.logic.landseaserver.ws.dto.PropertyDTO;
import com.logic.landseaserver.ws.dto.RemouldProjectDTO;
import com.logic.landseaserver.ws.dto.RemouldProjectListDTO;
import com.logic.landseaserver.ws.dto.ReportStripDTO;
import com.logic.system.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Path("/remouldProject")
@Api(value="remouldProject")
public class RemouldProjectRest {
	@Autowired
	private IRemouldProjectService remouldProjectServiceImpl;

	@Autowired
	private IProperty propertyServiceImpl;

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IReportStripService reportStripService;

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Create a new remouldProject")
	public Response create(@ApiParam(value = "param", required = true) RemouldProject remouldProject) {
		CommonResultMap map = new CommonResultMap();
		try {
			int id = remouldProjectServiceImpl.insert(remouldProject);
			remouldProject.setId(id);
			map.setData(remouldProjectServiceImpl.getDTO(id));
			map.setResult(CommonResult.SUCCESS, "Create success");
		} catch (BusinessException e) {
		    logger.error("create error.", e);
			map.setResult(e);
		}  catch (Exception e) {
		    logger.error("create error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}


	@DELETE
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "logic delete remouldProject by set deleted")
	public Response logicDelete(@ApiParam(value = "param", required = true) @QueryParam("remouldProjectId") String ids) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.delete(ids);
			map.setResult(CommonResult.SUCCESS,"delete remouldProject");
		} catch (Exception e) {
		    logger.error("logicDelete error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "edit remouldProject ")
	public Response update(@ApiParam(value = "param", required = true) RemouldProject remouldProject) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.update(remouldProject);
			map.setResult(CommonResult.SUCCESS,"edit remouldProject");
		} catch (Exception e) {
		    logger.error("update error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@GET
	@Path("/detail/{remouldProjectId}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Get remouldProject by remouldProject id")
	public Response retrieveDTO(
			@ApiParam(value = "param", required = true) @PathParam("remouldProjectId") Integer remouldProjectId) {
		CommonResultMap map = new CommonResultMap();
		try {
			map.setData(remouldProjectServiceImpl.getDTO(remouldProjectId));
			map.setResult(CommonResult.SUCCESS);
		} catch (Exception e) {
		    logger.error("retrieveDTO error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	//项目变更
	@GET
	@Path("/change/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Change remouldProjectProcedure by remouldProject id")
	public Response changeRemouldProject(
			@ApiParam(value = "param", required = true) @PathParam("id") Integer id) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.changeRemouldProject(id);
			map.setResult(CommonResult.SUCCESS);
		} catch (Exception e) {
		    logger.error("changeRemouldProject error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/detail/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list remouldProjects")
	public Response listDTO(@ApiParam(value = "param", required = true) QueryUtil queryUtil){
		CommonResultMap map = new CommonResultMap();
		List<RemouldProjectDTO> remouldProjectList = null;
		try {
			queryUtil.getPagingTool().calculateStartIndex();
			ResetQueryUtil.reset(queryUtil);
			remouldProjectList = remouldProjectServiceImpl.queryDTO(queryUtil);
			Integer totalCount = queryUtil.getPagingTool().getTotalNum();
			map.setData(remouldProjectList);
			map.setResultTotalCount(totalCount);
			map.setResult(CommonResult.SUCCESS);

		} catch (Exception e) {
		    logger.error("listDTO error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/{projectId}/procedure")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "add procedure to project")
	public Response addProcedure(@ApiParam(value = "param", required = true) @PathParam("projectId") Integer projectId,
			@ApiParam(value = "param", required = true) Procedure newProcedure) {
		CommonResultMap map = new CommonResultMap();
		try {
			newProcedure.setSerialNum(System.currentTimeMillis() + "");
			Procedure procedure = remouldProjectServiceImpl.addProcedure(projectId, newProcedure);
			map.setData(procedure);
			map.setResult(CommonResult.SUCCESS, "add success");
		} catch (BusinessException e) {
		    logger.error("addProcedure error.", e);
			map.setResult(e);
		}  catch (Exception e) {
		    logger.error("addProcedure error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@PUT
	@Path("/{projectId}/procedure/batch")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "choose procedure to project")
	public Response batchChooseProcedure(@ApiParam(value = "param", required = true) @PathParam("projectId") Integer projectId,
			@ApiParam(value = "param", required = true) @QueryParam("procedureIds") String procedureIds) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.addProcedure(projectId, procedureIds);
			map.setResult(CommonResult.SUCCESS, "update success");
		} catch (BusinessException e) {
		    logger.error("batchChooseProcedure error.", e);
			map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
		} catch (Exception e) {
		    logger.error("batchChooseProcedure error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@DELETE
	@Path("/{projectId}/procedure/batch")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "add procedure to project")
	public Response batchRemoveProcedure(@ApiParam(value = "param", required = true) @PathParam("projectId") Integer projectId,
			@ApiParam(value = "param", required = true) @QueryParam("procedureIds") String procedureIds) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.removeProcedure(projectId, procedureIds);
			map.setResult(CommonResult.SUCCESS, "delete success");
		} catch (Exception e) {
		    logger.error("batchRemoveProcedure error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/{projectId}/procedures/batch")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "add procedures to project")
	public Response batchAddProcedure(@ApiParam(value = "param", required = true) @PathParam("projectId") Integer projectId,
			@ApiParam(value = "param", required = true) List<Procedure> newProcedure) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.batchAddProcedure(projectId, newProcedure);
			map.setResult(CommonResult.SUCCESS, "add success");
		} catch (BusinessException e) {
		    logger.error("batchAddProcedure error.", e);
			map.setResult(e);
		}  catch (Exception e) {
		    logger.error("batchAddProcedure error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/copy/{projectId}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Create a new project from template")
	public Response copy(
			@ApiParam(value = "param", required = true) @PathParam("projectId") Integer projectId) {
		CommonResultMap map = new CommonResultMap();
		try {
			map.setData(remouldProjectServiceImpl.copyFromTemplate(projectId));
			map.setResult(CommonResult.SUCCESS, "update success");
		} catch (BusinessException e) {
		    logger.error("copy error.", e);
			map.setResult(e);
		}  catch (Exception e) {
		    logger.error("copy error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@PUT
	@Path("/{projectId}/choose/{templateId}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Create a new project from template")
	public Response chooseTemplate(
			@ApiParam(value = "projectId", required = true) @PathParam("projectId") Integer projectId,
			@ApiParam(value = "templateId", required = true) @PathParam("templateId") Integer templateId) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.chooseTemplate(projectId, templateId);
			map.setResult(CommonResult.SUCCESS, "update success");
		} catch (BusinessException e) {
		    logger.error("chooseTemplate error.", e);
			map.setResult(e);
		}  catch (Exception e) {
		    logger.error("chooseTemplate error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@SuppressWarnings("unchecked")
	@GET
	@Path("/repair/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Get repair project")
	public Response retrieveRepairProject() {
		CommonResultMap map = new CommonResultMap();
		try {
			QueryUtil queryUtil = new QueryUtil();
			PagingTool pagingTool = new PagingTool();
			pagingTool.setCurrentPage(1);
			pagingTool.setPageSize(-1);
			pagingTool.calculateStartIndex();
			queryUtil.setPagingTool(pagingTool);
			QueryCriteria  queryCriteria = new QueryCriteria();
			queryCriteria.setConnection("and");
			queryCriteria.setKey("work_status");
			queryCriteria.setCondition("=");
			queryCriteria.setValue("R134");
			queryCriteria.setIsValueADigital(false);
			List<QueryCriteria> queryCriterias = new ArrayList<QueryCriteria>();
			queryCriterias.add(queryCriteria);
			queryUtil.setQueryCriterias(queryCriterias);
			List<RemouldProjectDTO> remouldProjectList = (List<RemouldProjectDTO>) remouldProjectServiceImpl.query(queryUtil);
			map.setData(remouldProjectList);
			map.setResult(CommonResult.SUCCESS);
		} catch (Exception e) {
		    logger.error("retrieveRepairProject error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/property/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list PSH5 property")
	public Response retrievePSH5Property(){
		CommonResultMap map = new CommonResultMap();
		try {
			QueryUtil queryUtil = new QueryUtil();
			PagingTool pagingTool = new PagingTool();
			pagingTool.setCurrentPage(1);
			pagingTool.setPageSize(-1);
			pagingTool.calculateStartIndex();
			queryUtil.setPagingTool(pagingTool);
			QueryCriteria  queryCriteria = new QueryCriteria();
			queryCriteria.setConnection("and");
			queryCriteria.setKey("statusCode");
			queryCriteria.setCondition("=");
			queryCriteria.setValue("PS5");
			queryCriteria.setIsValueADigital(false);
			List<QueryCriteria> queryCriterias = new ArrayList<QueryCriteria>();
			queryCriterias.add(queryCriteria);
			queryUtil.setQueryCriterias(queryCriterias);
			List<PropertyDTO> queryDTO = propertyServiceImpl.queryDTO(queryUtil);
			map.setData(queryDTO);
			map.setResult(CommonResult.SUCCESS);

		} catch (Exception e) {
		    logger.error("retrievePSH5Property error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@POST
	@Path("/user/list/{roleCode}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list roleUser property")
	public Response retrieveRoleUser(@ApiParam(value = "param", required = true) @PathParam("roleCode") String roleCode){
		CommonResultMap map = new CommonResultMap();
		try {
			QueryUtil queryUtil = new QueryUtil();
			PagingTool pagingTool = new PagingTool();
			pagingTool.setCurrentPage(1);
			pagingTool.setPageSize(-1);
			pagingTool.calculateStartIndex();
			queryUtil.setPagingTool(pagingTool);
			QueryCriteria  queryCriteria = new QueryCriteria();
			queryCriteria.setConnection("and");
			queryCriteria.setKey("role_code");
			queryCriteria.setCondition("like");
			queryCriteria.setValue(roleCode);
			queryCriteria.setIsValueADigital(false);
			List<QueryCriteria> queryCriterias = new ArrayList<QueryCriteria>();
			queryCriterias.add(queryCriteria);
			queryUtil.setQueryCriterias(queryCriterias);
			List<?> list = userService.query(queryUtil);
			map.setData(list);
			map.setResult(CommonResult.SUCCESS);

		} catch (Exception e) {
		    logger.error("retrieveRoleUser error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	//项目列表
	@POST
	@Path("/project/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list remouldProjects")
	public Response listProjectDTO(@ApiParam(value = "param", required = true) QueryUtil queryUtil){
		CommonResultMap map = new CommonResultMap();
		List<RemouldProjectListDTO> remouldProjectList = null;
		try {
			queryUtil.getPagingTool().calculateStartIndex();
			ResetQueryUtil.reset(queryUtil);
			remouldProjectList = remouldProjectServiceImpl.queryList(queryUtil);
			Integer totalCount = queryUtil.getPagingTool().getTotalNum();
			map.setData(remouldProjectList);
			map.setResultTotalCount(totalCount);
			map.setResult(CommonResult.SUCCESS);

		} catch (Exception e) {
		    logger.error("listProjectDTO error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

	@PUT
	@Path("/{newProjectId}/replace/{oldProjectId}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "use new project repalce old project contain procedure")
	public Response replace(
			@ApiParam(value = "param", required = true) @PathParam("newProjectId") Integer newProjectId,
			@ApiParam(value = "param", required = true) @PathParam("oldProjectId") Integer oldProjectId) {
		CommonResultMap map = new CommonResultMap();
		try {
			remouldProjectServiceImpl.replaceContent(newProjectId, oldProjectId);
			map.setResult(CommonResult.SUCCESS, "replace success");
		} catch (BusinessException e) {
		    logger.error("replace error.", e);
			map.setResult(e);
		}  catch (Exception e) {
		    logger.error("replace error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}
	
	//条线报告
	@POST
	@Path("/lineReportForm/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list line report form")
	public Response reportStrip(@ApiParam(value = "param", required = true) Integer id){
		CommonResultMap map = new CommonResultMap();
		try {
			String type="月报";
			List<ReportStripDTO> reportStrips = reportStripService.queryreportStrip(id,type);
			map.setData(reportStrips);
			map.setResult(CommonResult.SUCCESS);
		} catch (Exception e) {
		    logger.error("reportStrip error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}
	
	@POST
	@Path("/creat/lineReportForm/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Create a new lineReportForm")
	public Response createLineReportForm(@ApiParam(value = "param", required = true) ReportStrip reportStrip) {
		CommonResultMap map = new CommonResultMap();
		try {
			int id = reportStripService.insert(reportStrip);
			reportStrip.setId(id);
			map.setData(reportStripService.get(id));
			map.setResult(CommonResult.SUCCESS, "Create success");
		} catch (BusinessException e) {
		    logger.error("createLineReportForm error.", e);
			map.setResult(e);
		}  catch (Exception e) {
		    logger.error("createLineReportForm error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}
}
